package com.young.gpg.client.controller;

import com.jcraft.jsch.ChannelSftp;
import com.young.gpg.client.config.FtpProperties;
import com.young.gpg.client.config.GPGSecretKeyProperties;
import com.young.gpg.common.service.CommandService;
import com.young.gpg.common.util.SFTPUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @description：
 * @author: yangyahui01
 * @date: 12/5/24 10:44 AM
 */
@Slf4j
@RestController
public class TestController {

    @Resource
    private FtpProperties ftpProperties;

    @Resource
    private GPGSecretKeyProperties gpgSecretKeyProperties;

    @Autowired
    private CommandService commandService;

    @GetMapping("/testGpg")
    public void testGpg() {

        String fileName = "/Users/zhangwenwen/Desktop/huilv.py";
        boolean flag = commandService.gpgSignAndEncrypt(fileName, gpgSecretKeyProperties.getLocalUser(), gpgSecretKeyProperties.getRecipient(), gpgSecretKeyProperties.getPassWord());

        System.out.println(flag);

        boolean res = commandService.gpgDecrypt("/Users/zhangwenwen/Desktop/huilv.py.asc","/Users/zhangwenwen/Desktop/lala.txt", gpgSecretKeyProperties.getPassWord());

        System.out.println(res);



    }


    @GetMapping("/testUpload")
    public void testUpload(@RequestParam("fileName") String fileName) {


        String hostName = ftpProperties.getHostName();


        String userName = ftpProperties.getUserName();

        Integer port = ftpProperties.getPort();

        String sshKeyPath = ftpProperties.getSshKeyPath();


        SFTPUtil sftp = new SFTPUtil(userName, "", port, hostName, sshKeyPath, "");

        ChannelSftp channelSftp = sftp.privateKeyChannel();

        if (Objects.isNull(channelSftp)) {
            log.info("获取channel为空");
            return;
        }

        fileName = "/download/" + fileName;  //这个地址是该文件的绝对路径,根据实际情况修改


        try {
            boolean encrypt = commandService.gpgSignAndEncrypt(fileName, gpgSecretKeyProperties.getLocalUser(), gpgSecretKeyProperties.getRecipient(), gpgSecretKeyProperties.getPassWord());

            if (encrypt) {
                boolean flag = sftp.upload(ftpProperties.getUploadPath(), fileName + ".asc", channelSftp);

                log.info("上传加密文件到服务器:{}", flag);
            }
        } catch (Exception e) {
            log.error("系统错误:", e);
        } finally {
            channelSftp.disconnect();
        }
    }
}
